﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace SystemHelperLibrary.API.Msi
{
	public class MsiHelper : IDisposable
	{
		private IntPtr m_handle;

		public MsiHelper()
		{
			m_handle = IntPtr.Zero;
		}

		[StructLayout(LayoutKind.Sequential)]
		public struct MSIFILEHASHINFO
		{
			public int dwFileHashInfoSize;
			public int dwData0;
			public int dwData1;
			public int dwData2;
			public int dwData3;
		}

		[DllImport("msi.dll", SetLastError = true)]
		static extern int MsiOpenProduct(string szProduct, out IntPtr hProduct);

		[DllImport("msi.dll", CharSet = CharSet.Auto)]
		private static extern UInt32 MsiOpenPackage(string package, out IntPtr product);

		[DllImport("msi.dll", CharSet = CharSet.Auto)]
		private static extern UInt32 MsiOpenPackageEx(string package, int options, out IntPtr databaseHandle);

		[DllImport("msi.dll", CharSet = CharSet.Auto)]
		private static extern UInt32 MsiCloseHandle(IntPtr handle);

		[DllImport("msi.dll", CharSet = CharSet.Auto)]
		private static extern UInt32 MsiVerifyPackage(string package);

		[DllImport("msi.dll", CharSet = CharSet.Unicode)]
		static extern int MsiGetFileHash(string szFilePath, int dwOptions, out MSIFILEHASHINFO pHash);


		public void OpenProduct(string filePath)
		{
			MsiOpenProduct(filePath, out m_handle);
		}

		public MSIFILEHASHINFO MsiGetFileHashApi(string filePath)
		{
			MSIFILEHASHINFO info;
			MsiGetFileHash(filePath, 0, out info);
			return info;
		}

		public UInt32 VerifyPackage(string fPath)
		{
			return MsiVerifyPackage(fPath);
		}

		public void Dispose()
		{
			if (m_handle != IntPtr.Zero)
				MsiCloseHandle(m_handle);
		}
	}
}
